package com.xxx.yuedong.mine.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxx.yuedong.community.db.dao.DynamicDao;
import com.xxx.yuedong.community.db.dao.FollowDao;
import com.xxx.yuedong.community.pojo.Dynamic;
import com.xxx.yuedong.community.pojo.DynamicLike;
import com.xxx.yuedong.community.pojo.Follow;
import com.xxx.yuedong.mine.controller.form.UpdatePhoneForm;
import com.xxx.yuedong.mine.db.dao.*;
import com.xxx.yuedong.mine.pojo.*;
import com.xxx.yuedong.mine.pojo.vo.*;
import com.xxx.yuedong.mine.service.CommonService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 * @Author Lry
 * @Date 2023-08-02
 */

@Service
public class CommonServiceImpl implements CommonService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private FollowDao followDao;
    @Autowired
    private RunsDao runsDao;
    @Autowired
    private PlanDao planDao;
    @Autowired
    private CollectDao collectDao;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private Dynamic_likeDao dynamic_likeDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private DistrictDao districtDao;


    @Override
    public UserVO queryUserInfo(Long userId) {
        //根据用户id获取用户表的用户基本信息
        User user=userDao.selectById(userId);
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        //根据用户id获取该用户发动态的数量
        LambdaQueryWrapper<Dynamic> dynamicLambdaQueryWrapper=new LambdaQueryWrapper<>();
        dynamicLambdaQueryWrapper.eq(Dynamic::getUserId,userId);
        Integer dynamicNum=dynamicDao.selectCount(dynamicLambdaQueryWrapper);
        //根据用户id获取关注用户的数量
        LambdaQueryWrapper<Follow> followLambdaQueryWrapper=new LambdaQueryWrapper<>();
        followLambdaQueryWrapper.eq(Follow::getFromId,userId);
        Integer followNum=followDao.selectCount(followLambdaQueryWrapper);
        //根据用户id获取粉丝的数量
        followLambdaQueryWrapper=new LambdaQueryWrapper<>();
        followLambdaQueryWrapper.eq(Follow::getToId,userId);
        Integer fansNum=followDao.selectCount(followLambdaQueryWrapper);
        //根据用户id获取运动记录数据
        LambdaQueryWrapper<Runs> runsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        runsLambdaQueryWrapper.eq(Runs::getUser_id,userId);
        List<Runs> runs=runsDao.selectList(runsLambdaQueryWrapper);
        //创建数据不可重复的日期字符串集合
        Set<String> timeSet=new HashSet<>();
        Integer kcal=0;
        Integer min=0;
        Integer day=0;
        Integer second=0;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        for(Runs run:runs){
            //获取累计消耗的卡路里数量
            kcal+=run.getCalorie();
            //获取累计运动的秒数
            second+=run.getTime().getSecond()+run.getTime().getMinute()*60+run.getTime().getHour()*60*60;
            //将所查询到的每一条数据的日期格式化为：2023-02-02 这种格式后存入集合中，注意此集合会自动去重重复的日期字符串
            timeSet.add(sdf.format(run.getCreateTime()));
        }
        //将运动的秒数除60就是运动的分钟数
        min=second/60;
        //获取运动的总天数
        day=timeSet.size();

        userVO.setDay(day);
        userVO.setMin(min);
        userVO.setKcal(kcal);
        userVO.setFansNum(fansNum);
        userVO.setFollowNum(followNum);
        userVO.setDynamicNum(dynamicNum);

        return userVO;
    }

    @Override
    public void updateUserInfo(User user) {
        userDao.updateById(user);
    }

    @Override
    public List<Dynamic> queryDynamicList(Long userId) {
        LambdaQueryWrapper<Dynamic> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dynamic::getUserId,userId);
        List<Dynamic> dynamics=dynamicDao.selectList(lambdaQueryWrapper);
        return dynamics;
    }

    @Override
    public List<FollowVO> queryFollowList(Long userId) {
        return followDao.queryFollowList(userId);
    }

    @Override
    public void followUser(Long fromId, Long toId) {
        Follow follow=new Follow();
        follow.setFromId(fromId);
        follow.setToId(toId);
        followDao.insert(follow);

    }


    @Override
    public List<FansVO> queryFansList(Long userId) {
        List<FansVO> fansVOS=followDao.queryFansList(userId);
        return fansVOS;
    }

    @Override
    public RunVO querySportsCareerData(Long userId) {
        //根据用户id获取运动记录数据
        LambdaQueryWrapper<Runs> runsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        runsLambdaQueryWrapper.eq(Runs::getUser_id,userId);
        List<Runs> runs=runsDao.selectList(runsLambdaQueryWrapper);
        //创建不可重复的日期字符串集合容器
        Set<String> timeSet=new HashSet<>();
        Integer kcal=0;
        Integer min=0;
        Integer day=0;
        Integer second=0;
        Integer currentMouthStepNum=0;
        Integer currentMouthKcal=0;
        Integer currentMouthMin=0;
        //初始化总里程数变量
        BigDecimal totalMileage=new BigDecimal(0);
        Integer continuousDay=0;
        //创建日期格式化对象

        SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM");

        for(Runs run:runs){
            //获取运动记录的总秒数
            Integer hour=run.getTime().getHour();
            Integer minute=run.getTime().getMinute();
            Integer s=run.getTime().getSecond()+minute*60+hour*60*60;
            //累加运动总卡路里数
            kcal+=run.getCalorie();
            //获取累计秒数
            second+=s;
            //添加日期字符串
            timeSet.add(sdf.format(run.getCreateTime()));
            //累计添加总里程数
            totalMileage=totalMileage.add(run.getMileage());
            //获取本月的步数，消耗卡路里数和消耗分钟数
            if(sdf2.format(run.getCreateTime()).equals(sdf2.format(new Date()))){
                currentMouthStepNum+=run.getSteps();
                currentMouthKcal+=run.getCalorie();
                currentMouthMin+=s;
            }

        }
        //获取总分钟数
        min=second/60;
        day=timeSet.size();
        Date currentDate=new Date();
        //获取连续运动天数的逻辑
        for(;continuousDay<=day;continuousDay++){
           Date date=new Date(currentDate.getTime()-continuousDay*24*60*60*1000);
            if(!timeSet.contains(sdf.format(date))){
                break;
            }
        }
        RunVO runVO=new RunVO();
        runVO.setTotalDay(day);
        runVO.setTotalKcal(kcal);
        runVO.setTotalMin(min);
        runVO.setTotalMileage(totalMileage);
        runVO.setContinuousDay(continuousDay);
        runVO.setCurrentMouthKcal(currentMouthKcal);
        //秒数/60=分钟数
        runVO.setCurrentMouthMin(currentMouthMin/60);
        runVO.setCurrentMouthStepNum(currentMouthStepNum);
        return runVO;
    }

    @Override
    public List<PlanVO> queryMyPlan(Long userId, String date) {
        List<PlanVO> list=planDao.queryMyPlan(userId,date);
        return list;
    }

    @Override
    public List<CollectVO> queryMyCollect(Long userId, String tag) {
        List<CollectVO> list=planDao.queryMyCollect(userId,tag);

        return list;
    }

    @Override
    public Set<String> queryMyCourseTags(Long userId) {
        List<CollectVO> list=planDao.queryMyCollect(userId,null);
        Set<String> tags=new HashSet<>();
        list.forEach(data->{
            tags.addAll(JSONObject.parseArray(data.getTags(),String.class));
        });
        return tags;
    }

    @Override
    public void collectCourse(Long userId, Long courseId) {
        Collect collect=new Collect();
        collect.setCourse_id(courseId);
        collect.setUser_id(userId);
        collectDao.insert(collect);
    }

    @Override
    public CourseVO queryCourseDetail(Long userId, Long courseId) {
        CourseVO courseVO=courseDao.queryCourseDetail(userId,courseId);
        return courseVO;
    }

    @Override
    public List<OrderVO> queryOrderList(Long userId) {
        List<OrderVO> list=orderDao.queryOrderList(userId);
        return list;
    }

    @Override
    public void updatePhone(UpdatePhoneForm phoneForm) {
        User user = new User();
        user.setId(phoneForm.getUserId());
        user.setPhone(phoneForm.getPhone());
        userDao.updateById(user);
    }

    @Override
    public Integer queryUserLikeDynamicNum(Long userId) {
        LambdaQueryWrapper<Dynamic_like> dynamicLikeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        dynamicLikeLambdaQueryWrapper.eq(Dynamic_like::getUser_id,userId);
        return  dynamic_likeDao.selectCount(dynamicLikeLambdaQueryWrapper);

    }

    @Override
    public List<Dynamic> queryUserLikeDynamicList(Long userId) {
        LambdaQueryWrapper<Dynamic_like> dynamicLikeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        dynamicLikeLambdaQueryWrapper.eq(Dynamic_like::getUser_id,userId);
        List<Dynamic_like> list=dynamic_likeDao.selectList(dynamicLikeLambdaQueryWrapper);
        if(list.size()==0)return new ArrayList<>();
        List<Long> ids=new ArrayList<>();
        list.forEach(data->ids.add(data.getDynamic_id()));

        LambdaQueryWrapper<Dynamic> dynamicLambdaQueryWrapper=new LambdaQueryWrapper<>();
        dynamicLambdaQueryWrapper.in(Dynamic::getId,ids);
        return dynamicDao.selectList(dynamicLambdaQueryWrapper);
    }

    @Override
    public List<AddressVO> queryMyAddress(Long userId) {
        return addressDao.queryMyAddress(userId);
    }

    @Override
    public void saveAddress(Address address) {
        addressDao.insert(address);
    }

    @Override
    public void updateAddress(Address address) {
          addressDao.updateById(address);
    }

    @Override
    public void deleteAddress(Long id) {
          addressDao.deleteById(id);
    }


}
